<template>
  <div>
    <el-breadcrumb class="mb-30px text-16px">
      <el-breadcrumb-item :to="{ path: '/back/info' }"
        >信息管理</el-breadcrumb-item
      >
      <el-breadcrumb-item>{{ breadcrumbMap() }}</el-breadcrumb-item>
    </el-breadcrumb>
    <div v-if="form.page_type === 'detail'">
      <div
        class="flex flex-justify-center flex-items-center text-20px mb-20px font-600"
      >
        {{ form.title }}
      </div>
      <div class="flex flex-justify-center flex-items-center text-18px mb-20px">
        <div class="mr-30px">发布时间：{{ form.ctime }}</div>
        <div class="mr-30px">来源：{{ form.source }}</div>
        <div class="mr-30px">点击数：{{ form.clicks }}</div>
      </div>
      <div v-html="form.content" id="wrap"></div>
    </div>
    <div v-if="form.page_type !== 'detail'">
      <el-form :inline="true" :model="form" :rules="rules">
        <el-form-item label="标题:" prop="title">
          <el-input v-model="form.title" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="新闻类型:" prop="type">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option
              v-for="item in selectType"
              :label="item.label"
              :value="item.value"
              :key="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="来源:">
          <el-input v-model="form.source" placeholder="请输入" clearable />
        </el-form-item>

        <el-form-item label="跳转url:">
          <el-input v-model="form.url" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="发布时间:">
          <el-date-picker
            v-model="form.ctime"
            type="date"
            placeholder="请选择"
          />
        </el-form-item>
        <el-form-item v-if="form.page_type !== detail">
          <el-button type="primary" @click="submit">发布</el-button>
        </el-form-item>
      </el-form>

      <Editor v-model="form.content" />
      <div class="flex flex-items-center mt-20px">
        <div class="text-18px mr-300px">
          <div class="mr-10px mt--15px">封面图片:</div>
          <el-upload
            v-model:file-list="imgList"
            accept=".png, .jpg, .jpeg"
            class="mt-20px"
            :before-upload="beforeUpload"
            :on-remove="handleRemove"
            list-type="picture"
          >
            <el-button type="primary">点击上传图片</el-button>
          </el-upload>
        </div>
        <div class="text-18px">
          <div class="mr-10px ml-20px">文件列表:</div>
          <el-upload
            class="upload-demo mt-20px"
            drag
            action="#"
            :multiple="false"
            :show-file-list="true"
            :http-request="uploadHttpRequest"
            :on-change="handleUploadChange"
            :file-list="form.files"
            :on-remove="handleRemoveFile"
          >
            <el-button slot="trigger" type="primary">点击上传文件</el-button>
          </el-upload>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { ElNotification, dayjs } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import * as imageConversion from "image-conversion";
import {
  add_news,
  news_detail,
  update_news,
  delete_news_file,
} from "@/api/back/news";
import { upload_file } from "@/api/back/news";
import { selectType, rules } from "../data.config";

const imgList = ref([]);
let fileList = [];
const form = reactive({
  id: "",
  page_type: "detail",
  title: "",
  content: "",
  type: "news",
  source: "",
  url: "",
  ctime: dayjs(new Date()).format("YYYY-MM-DD"),
  header_img: "",
  files: [],
});

const $router = useRouter();
const $route = useRoute();

// console.log('$route', $route.query.type);

const detail = async () => {
  // const { data } = await news_detail({ id: form.id });
  // fileList = data.files.map(({ name, file_id }) => ({
  //   name,
  //   file_id,
  // }));

  // Object.keys(data).forEach((key) => {
  //   form[key] = data[key];
  // });
  // imgList.value = data.header_img
  //   ? [{ name: "封面图片", url: data.header_img }]
  //   : [];
};

form.page_type = $route.query.type;

watch(
  () => $route.fullPath,
  (newValue: any) => {
    form.id = $route.query.id;
    form.page_type = $route.query.type;
    console.log("newValue", newValue, $route.query.type);
    if (["edit", "detail"].includes($route.query.type)) {
      detail();
    } else {
      Object.keys(form).forEach((key) => {
        form[key] = "";
        form.files = [];
        form.ctime = dayjs(new Date()).format("YYYY-MM-DD");
      });
    }
  },
  { immediate: true }
);

const breadcrumbMap = () => {
  const types = {
    add: "新增新闻",
    edit: "编辑新闻",
    detail: "新闻详情",
  };
  return types[form.page_type] || "编辑新闻";
};

const handleRemoveFile = async (file) => {
  const file_id = fileList.filter((item) => item.name === file.name)[0].file_id;
  const { data } = await delete_news_file({ id, file_id });
  form.files = [];
};

const handleRemove = (file) => {
  file.url = "";
  form.header_img = "";
};

const toBase64 = (file) => {
  let reader = new FileReader();
  reader.onloadend = function () {
    imgList.value = [];
    form.header_img = reader.result;
    imgList.value = [{ name: "封面图片", url: form.header_img }];
  };
  if (file) {
    reader.readAsDataURL(file);
  }
};
const uploadHttpRequest = (data) => {
  let reader = new FileReader();
  reader.readAsText(data.file);
  reader.onload = function () {};
};

const handleUploadChange = async (file) => {
  let upfile = file.raw;
  let formData = new FormData();
  formData.append("file", upfile);
  const { data } = await upload_file(formData);
  form.files.push({ file_id: data.id, name: data.name });
};

const beforeUpload = (file) => {
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isLt2M) {
    ElNotification.error("上传图片大小不能超过2MB");
    return false;
  } else {
    const isSize = new Promise((resolve, reject) => {
      const _URL = window.URL || window.webkitURL;
      const img = new Image();
      img.onload = () => {
        const valid = true;
        valid ? resolve() : reject();
      };
      img.src = _URL.createObjectURL(file);
    }).then(
      () => {
        return file;
      },
      () => {
        ElNotification.error("上传图片大小不能超过2MB");
        return Promise.reject();
      }
    );
    // return isSize;
    isSize.then((file) => {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 < 100;
      if (!isJpgOrPng) {
        ElNotification.error("上传图片只能是 JPG 或 PNG 格式!");
        return false;
      }
      return new Promise((resolve) => {
        // 小于100KB 不压缩
        if (isLt2M) {
          resolve(file);
        }
        // 压缩到200KB,这里的200就是要压缩的大小,可自定义
        imageConversion.compressAccurately(file, 50).then((res: any) => {
          toBase64(res);
          resolve(res);
        });
      });
    });
  }
  // this.toBase64(file);
  return false; //取消自动上传
};

const submit = async () => {
  form.ctime = dayjs(form.ctime).format("YYYY-MM-DD");

  if ($route.query.type === "add") {
    const { code } = await add_news(form, form.id);
    if (code === 200) {
      ElNotification.success("新增成功");
      Object.keys(form).forEach((key) => {
        (form[key] = ""), (form.ctime = dayjs(new Date()).format("YYYY-MM-DD"));
      });
      form.page_type = "detail";

      $router.push("/back/info");
    } else {
      ElNotification.error("新增失败");
    }
  } else {
    const { code } = await update_news({ ...form, id: form.id });
    if (code === 200) {
      ElNotification({
        duration: 1500,
        type: "success",
        message: "修改成功",
      });
      Object.keys(form).forEach((key) => {
        (form[key] = ""), (form.ctime = dayjs(new Date()).format("YYYY-MM-DD"));
        form.files = [];
        imgList.value = [];
      });
      fileList = [];
      form.page_type = "detail";

      $router.push("/back/info");
    } else {
      ElNotification.error("修改失败");
    }
  }
};
</script>

<style scoped lang="scss">
:deep .el-upload-dragger {
  width: 150px;
  padding: 0;
  border: none;
}
/* table 样式 */
#wrap :deep table {
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  line-height: 30px;
  padding: 3px 5px;
}
#wrap :deep table tr:first-child {
  background-color: #f5f2f0;
  font-weight: bolder;
  font-size: 16px;
}
#wrap :deep table tr {
  font-size: 16px;
  min-height: 30px;
}
#wrap :deep table td,
table th {
  line-height: 30px;
  padding: 3px 5px;
  border-bottom: 1px solid #ccc;
  border-right: 1px solid #ccc;
  padding: 3px 5px;
}
#wrap :deep table th {
  border-bottom: 1px solid #ccc;
  border-right: 1px solid #ccc;
  // text-align: center;
  line-height: 30px;
  padding: 3px 5px;
}

/* blockquote 样式 */
blockquote {
  display: block;
  border-left: 8px solid #d0e5f2;
  padding: 5px 10px;
  margin: 10px 0;
  line-height: 1.4;
  font-size: 100%;
  background-color: #f1f1f1;
}

/* code 样式 */
code {
  display: inline-block;
  *display: inline;
  *zoom: 1;
  background-color: #f1f1f1;
  border-radius: 3px;
  padding: 3px 5px;
  margin: 0 3px;
}
pre code {
  display: block;
}

/* ul ol 样式 */
ul,
ol {
  margin: 10px 0 10px 20px;
}
</style>
